//
//  MapaviewController.m
//  iFarmacia
//
//  Created by Jose Lino on 12/8/10.
//  Copyright 2010 Skymedia. All rights reserved.
//

#import "MapaviewController.h"
#import "MeuPinView.h"
#import "MeuPino.h"
#import <CoreLocation/CoreLocation.h>

@implementation MapaviewController

- (void)viewDidLoad {

	locationManager=[[CLLocationManager alloc] init];
	locationManager.desiredAccuracy = kCLLocationAccuracyBest;
	locationManager.delegate=self;
	[locationManager startUpdatingLocation];

	[UIApplication sharedApplication].statusBarHidden = YES;
    [super viewDidLoad];
	
	if (self = [super init]) 
			self.title = @"Mapas";

	//[UIApplication sharedApplication].statusBarHidden = NO;
	
	dicDados = [[NSMutableDictionary alloc] init];
	myDados = [[Dados alloc] init];
	[self initWithObject:[myDados readFarmFromDatabase]];

}

-(void)mostrarPino {
	[self adicionarPinComImagem:[UIImage imageNamed:@"balao_ponto.png"] titulo:[dicDados objectForKey:@"nome"] subTitulo:nil idestabelecimento:[[dicDados objectForKey:@"id"] intValue]];
}


-(void)adicionarPinComImagem:(UIImage*)imagemPino titulo:(NSString*)oTitulo subTitulo:(NSString*)oSubTitulo idestabelecimento:(NSInteger)oId {
	
	MeuPino *novoPin = [[MeuPino alloc] init];
	novoPin.title = oTitulo;
	novoPin.subtitle = oSubTitulo;
	novoPin.coordinate = localizacaoFarm;
	novoPin.imagemPino = imagemPino;
	novoPin.idestabelecimento = oId;
	[meuMapa addAnnotation:novoPin];
	
}

- (MKAnnotationView*)mapView:(MKMapView *)mapView viewForAnnotation:(id )annotation {
	
	MeuPino* MeuPin = (MeuPino *)annotation;
	//MeuPin.
	NSString* identifier = @"Meu Pin";
	MeuPinView *viewDoPino = (MeuPinView *)[meuMapa dequeueReusableAnnotationViewWithIdentifier:identifier];
	
	if(viewDoPino == nil) 
		viewDoPino = [[[MeuPinView alloc] initWithAnnotation:MeuPin reuseIdentifier:identifier] autorelease];
	
	[viewDoPino setEnabled:YES];
	[viewDoPino setCanShowCallout:YES];
	
	return viewDoPino;
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
	
	//para ser usado com um toque no ponto do mapa
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	dicDados = nil;
    [super dealloc];
}


#pragma mark -
#pragma mark Objeto

- (void) initWithObject:(NSMutableArray *) array
{
	dicDados = [[NSMutableDictionary alloc] init];
	
	NSString *Id, *Nome, *latitude, *longitude, *aLat, *aLon;
	NSMutableArray *arrayDados = [[NSMutableArray alloc] init];
	
	NSLog(@"array: %@", array);
	int i;
	for (i=0; i<[array count]; i++) {

		farmObj = [array objectAtIndex:i];
		arrLL = [farmObj.farmLLString componentsSeparatedByString:@","];
		
		aLat = [arrLL objectAtIndex:0];
		float fLat = [aLat floatValue];
		
		aLon = [arrLL objectAtIndex:1];
		float fLon = [aLon floatValue];
		
		Id = [NSString stringWithFormat:@"%d", farmObj.farmID];
		Nome = farmObj.farmNome;
		latitude = [NSString stringWithFormat:@"%f", fLat];
		longitude = [NSString stringWithFormat:@"%f", fLon];
		
		NSDictionary *myDictConfig = [NSDictionary dictionaryWithObjectsAndKeys:
									  Id, @"id",
									  Nome, @"nome",
									  latitude, @"latitude",
									  longitude, @"longitude",
									  nil];
		
		[arrayDados addObject:myDictConfig];	
		[myDictConfig release];

		
	}

	int valArr = [arrayDados count] > 9 ? 10 : [arrayDados count];
	
	for (int i = 0 ; i<valArr; i++) {

		[dicDados setObject:[[arrayDados objectAtIndex:i] copy] forKey:[NSString stringWithFormat:@"%d",i]];
		NSLog(@"DictDados %@", dicDados);
	}
	
	NSDictionary *masterDict = [[NSDictionary alloc] init];
	
	for (int i=0; i<[dicDados count]; i++) {
		
		masterDict = [dicDados objectForKey:[NSString stringWithFormat:@"%d", i]];
		NSLog(@"nome: %@", [masterDict objectForKey:@"nome"]);	
		
		localizacaoFarm.latitude = [[masterDict objectForKey:@"latitude"] floatValue];
		localizacaoFarm.longitude = [[masterDict objectForKey:@"longitude"] floatValue];
		
		[self adicionarPinComImagem:[UIImage imageNamed:@"balao_ponto.png"] titulo:[masterDict objectForKey:@"nome"] subTitulo:nil idestabelecimento:[[masterDict objectForKey:@"id"] intValue] ];
	}

	
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
	
	// Parar com as atualizacoes de localizacao para economizar bateria
	[manager stopUpdatingLocation];
	
	latitudeAtual = newLocation.coordinate.latitude;
	longitudeAtual = newLocation.coordinate.longitude;
	
	localizacaoAtual.latitude = latitudeAtual; 
	localizacaoAtual.longitude = longitudeAtual;
	// Setar regiao do mapa com centro definido acima e span definido em linha
	[meuMapa setRegion:MKCoordinateRegionMake(localizacaoAtual, MKCoordinateSpanMake(0.01, 0.01)) animated:YES];
	
}
@end
